#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
脚本：将txt文件内容通过本地API服务器发送
功能：读取txt文件，启动本地HTTP服务器，提供API接口供前端获取数据
"""

import json
import os
import sys
import time
from http.server import HTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
import signal
import logging

# 配置日志 - 仅输出到控制台
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

class TxtDataAPIHandler(BaseHTTPRequestHandler):
    """处理API请求的HTTP服务器"""
    
    # 类变量存储txt数据
    txt_data = None
    smis_data = None
    u9_orders_data = None
    smis_work_order_materials_data = None
    
    def do_GET(self):
        """处理GET请求"""
        try:
            parsed_url = urlparse(self.path)
            
            # 处理工单数据API请求
            if parsed_url.path == '/api/work-orders-from-txt':
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
                self.end_headers()
                
                # 返回txt文件内容
                if self.txt_data:
                    # 检查txt_data的结构，如果是包含data字段的对象，则提取data字段
                    actual_data = self.txt_data
                    if isinstance(self.txt_data, dict) and 'data' in self.txt_data:
                        actual_data = self.txt_data['data']
                        logger.info(f"从txt_data对象中提取data字段，类型: {type(actual_data).__name__}，长度: {len(actual_data) if isinstance(actual_data, list) else 'N/A'}")
                    
                    response_data = {
                        'success': True,
                        'data': actual_data,
                        'message': '成功获取工单数据',
                        'timestamp': int(time.time()),
                        'count': len(actual_data) if isinstance(actual_data, list) else 1
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                else:
                    response_data = {
                        'success': False,
                        'data': [],
                        'message': '未找到工单数据',
                        'timestamp': int(time.time()),
                        'count': 0
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                    
                logger.info(f"API请求成功: {self.client_address[0]} - {parsed_url.path}")
                
            elif parsed_url.path == '/api/smis-inventory':
                # 处理SMIS配料岛库存数据API请求
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
                self.end_headers()
                
                # 返回SMIS配料岛库存数据
                if self.smis_data:
                    # 检查smis_data的结构，如果是包含data字段的对象，则提取data字段
                    actual_data = self.smis_data
                    if isinstance(self.smis_data, dict) and 'data' in self.smis_data:
                        actual_data = self.smis_data['data']
                        logger.info(f"从smis_data对象中提取data字段，类型: {type(actual_data).__name__}，长度: {len(actual_data) if isinstance(actual_data, list) else 'N/A'}")
                    
                    response_data = {
                        'success': True,
                        'data': actual_data,
                        'message': '成功获取SMIS配料岛库存数据',
                        'timestamp': int(time.time()),
                        'count': len(actual_data) if isinstance(actual_data, list) else 1
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                else:
                    response_data = {
                        'success': False,
                        'data': [],
                        'message': '未找到SMIS配料岛库存数据',
                        'timestamp': int(time.time()),
                        'count': 0
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                    
                logger.info(f"SMIS配料岛库存API请求成功: {self.client_address[0]} - {parsed_url.path}")
                
            elif parsed_url.path == '/api/u9-production-orders':
                # 处理U9生产订单数据API请求
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
                self.end_headers()
                
                # 返回U9生产订单原始数据（不进行解析）
                if self.u9_orders_data:
                    response_data = {
                        'success': True,
                        'data': self.u9_orders_data,
                        'message': '成功获取U9生产订单原始数据',
                        'timestamp': int(time.time()),
                        'count': 1  # 原始数据计数为1
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                else:
                    response_data = {
                        'success': False,
                        'data': [],
                        'message': '未找到U9生产订单数据',
                        'timestamp': int(time.time()),
                        'count': 0
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                    
                logger.info(f"U9生产订单API请求成功: {self.client_address[0]} - {parsed_url.path}")
                
            elif parsed_url.path == '/api/smis-work-order-materials':
                # 处理SMIS工单物料数据API请求
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
                self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
                self.end_headers()
                
                # 解析查询参数
                query_params = parse_qs(parsed_url.query)
                orderno_filter = query_params.get('orderno', [None])[0]  # 获取orderno参数
                
                # 返回SMIS工单物料数据
                if self.smis_work_order_materials_data:
                    # 检查数据结构，如果是包含data字段的对象，则提取data字段
                    actual_data = self.smis_work_order_materials_data
                    if isinstance(self.smis_work_order_materials_data, dict) and 'data' in self.smis_work_order_materials_data:
                        actual_data = self.smis_work_order_materials_data['data']
                        logger.info(f"从smis_work_order_materials_data对象中提取data字段，类型: {type(actual_data).__name__}，长度: {len(actual_data) if isinstance(actual_data, list) else 'N/A'}")
                    
                    # 根据orderno参数过滤数据
                    filtered_data = actual_data
                    if orderno_filter and isinstance(actual_data, list):
                        filtered_data = [item for item in actual_data if item.get('orderno') == orderno_filter]
                        logger.info(f"根据orderno={orderno_filter}过滤数据，过滤后数量: {len(filtered_data)}")
                    elif orderno_filter and isinstance(actual_data, dict) and actual_data.get('orderno') != orderno_filter:
                        filtered_data = []
                        logger.info(f"根据orderno={orderno_filter}过滤数据，单条数据不匹配")
                    
                    response_message = '成功获取SMIS工单物料数据'
                    if orderno_filter:
                        response_message += f' (工单号: {orderno_filter})'
                    
                    response_data = {
                        'success': True,
                        'data': filtered_data,
                        'message': response_message,
                        'timestamp': int(time.time()),
                        'count': len(filtered_data) if isinstance(filtered_data, list) else 1
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                else:
                    response_data = {
                        'success': False,
                        'data': [],
                        'message': '未找到SMIS工单物料数据',
                        'timestamp': int(time.time()),
                        'count': 0
                    }
                    response_json = json.dumps(response_data, ensure_ascii=False, indent=2)
                    self.wfile.write(response_json.encode('utf-8'))
                    
                logger.info(f"SMIS工单物料API请求成功: {self.client_address[0]} - {parsed_url.path}{('?orderno=' + orderno_filter) if orderno_filter else ''}")
                
            elif parsed_url.path == '/api/health':
                # 健康检查接口
                self.send_response(200)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                health_data = {
                    'status': 'healthy',
                    'timestamp': int(time.time()),
                    'data_loaded': self.txt_data is not None,
                    'data_count': len(self.txt_data) if isinstance(self.txt_data, list) else (1 if self.txt_data else 0),
                    'smis_data_loaded': self.smis_data is not None,
                    'smis_data_count': len(self.smis_data) if isinstance(self.smis_data, list) else (1 if self.smis_data else 0),
                    'u9_orders_data_loaded': self.u9_orders_data is not None,
                    'u9_orders_data_count': 1 if self.u9_orders_data else 0,  # 原始数据计数为1
                    'smis_work_order_materials_data_loaded': self.smis_work_order_materials_data is not None,
                    'smis_work_order_materials_data_count': len(self.smis_work_order_materials_data) if isinstance(self.smis_work_order_materials_data, list) else (1 if self.smis_work_order_materials_data else 0)
                }
                response_json = json.dumps(health_data, ensure_ascii=False, indent=2)
                self.wfile.write(response_json.encode('utf-8'))
                
            elif parsed_url.path == '/':
                # 根路径 - 显示API信息
                self.send_response(200)
                self.send_header('Content-Type', 'text/html; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                html_content = f"""
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>工单数据API服务器</title>
    <style>
        body {{ font-family: Arial, sans-serif; margin: 40px; background-color: #f5f5f5; }}
        .container {{ max-width: 800px; margin: 0 auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }}
        .header {{ text-align: center; color: #333; margin-bottom: 30px; }}
        .api-info {{ background: #f8f9fa; padding: 20px; border-radius: 6px; margin: 20px 0; }}
        .api-url {{ font-family: monospace; background: #e9ecef; padding: 10px; border-radius: 4px; }}
        .status {{ color: #28a745; font-weight: bold; }}
        .count {{ color: #007bff; font-weight: bold; }}
        .footer {{ text-align: center; margin-top: 30px; color: #666; }}
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 工单数据API服务器</h1>
            <p>为前端提供txt文件数据的API接口</p>
        </div>
        
        <div class="api-info">
            <h3>📡 API接口信息</h3>
            <p><strong>工单数据接口：</strong></p>
            <div class="api-url">GET /api/work-orders-from-txt</div>
            <p><strong>SMIS配料岛库存接口：</strong></p>
            <div class="api-url">GET /api/smis-inventory</div>
            <p><strong>SMIS工单物料接口：</strong></p>
            <div class="api-url">GET /api/smis-work-order-materials</div>
            <div class="api-url">GET /api/smis-work-order-materials?orderno=工单号</div>
            <p><strong>U9生产订单接口：</strong></p>
            <div class="api-url">GET /api/u9-production-orders</div>
            <p><strong>健康检查接口：</strong></p>
            <div class="api-url">GET /api/health</div>
        </div>
        
        <div class="api-info">
            <h3>📊 数据状态</h3>
            <p><strong>SMIS工单数据：</strong> <span class="status">{'已加载' if self.txt_data else '未加载'}</span> - <span class="count">{len(self.txt_data) if isinstance(self.txt_data, list) else (1 if self.txt_data else 0)} 条</span></p>
            <p><strong>SMIS配料岛库存：</strong> <span class="status">{'已加载' if self.smis_data else '未加载'}</span> - <span class="count">{len(self.smis_data) if isinstance(self.smis_data, list) else (1 if self.smis_data else 0)} 条</span></p>
            <p><strong>SMIS工单物料：</strong> <span class="status">{'已加载' if self.smis_work_order_materials_data else '未加载'}</span> - <span class="count">{len(self.smis_work_order_materials_data) if isinstance(self.smis_work_order_materials_data, list) else (1 if self.smis_work_order_materials_data else 0)} 条</span></p>
            <p><strong>U9生产订单：</strong> <span class="status">{'已加载' if self.u9_orders_data else '未加载'}</span> - <span class="count">{1 if self.u9_orders_data else 0} 个原始文件</span></p>
            <p><strong>时间：</strong> {time.strftime('%Y-%m-%d %H:%M:%S')}</p>
        </div>
        
        <div class="api-info">
            <h3>🔧 前端集成</h3>
            <p>在您的前端项目中，可以通过以下方式获取数据：</p>
            <pre style="background: #f8f9fa; padding: 15px; border-radius: 4px; overflow-x: auto;">
// 使用fetch获取数据
fetch('/api/work-orders-from-txt')
  .then(response => response.json())
  .then(data => {{
    if (data.success) {{
      console.log('工单数据：', data.data);
    }}
  }});
            </pre>
        </div>
        
        <div class="footer">
            <p>🛠️ 工单管理系统 | 数据API服务器</p>
        </div>
    </div>
</body>
</html>
                """
                self.wfile.write(html_content.encode('utf-8'))
                
            else:
                # 404 错误
                self.send_response(404)
                self.send_header('Content-Type', 'application/json; charset=utf-8')
                self.send_header('Access-Control-Allow-Origin', '*')
                self.end_headers()
                
                error_data = {
                    'success': False,
                    'message': f'未找到路由: {parsed_url.path}',
                    'timestamp': int(time.time()),
                    'available_routes': ['/api/work-orders-from-txt', '/api/smis-inventory', '/api/smis-work-order-materials', '/api/u9-production-orders', '/api/health', '/']
                }
                response_json = json.dumps(error_data, ensure_ascii=False, indent=2)
                self.wfile.write(response_json.encode('utf-8'))
                
        except Exception as e:
            logger.error(f"处理GET请求时发生错误: {e}")
            self.send_response(500)
            self.send_header('Content-Type', 'application/json; charset=utf-8')
            self.send_header('Access-Control-Allow-Origin', '*')
            self.end_headers()
            
            error_data = {
                'success': False,
                'message': f'服务器内部错误: {str(e)}',
                'timestamp': int(time.time())
            }
            response_json = json.dumps(error_data, ensure_ascii=False, indent=2)
            self.wfile.write(response_json.encode('utf-8'))
    
    def do_OPTIONS(self):
        """处理OPTIONS请求（CORS预检）"""
        self.send_response(200)
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type, Authorization')
        self.end_headers()
    
    def log_message(self, format, *args):
        """重写日志方法以使用我们的logger"""
        logger.info(f"{self.client_address[0]} - {format % args}")

def read_txt_file(file_path):
    """读取txt文件内容并解析JSON"""
    try:
        with open(file_path, 'r', encoding='utf-8') as f:
            content = f.read().strip()
            
        logger.info(f"成功读取txt文件: {file_path}，内容长度: {len(content)}")
        
        # 尝试解析JSON内容
        try:
            parsed_data = json.loads(content)
            logger.info(f"成功解析JSON数据，类型: {type(parsed_data).__name__}")
            return parsed_data
        except json.JSONDecodeError as e:
            logger.warning(f"JSON解析失败: {e}，返回原始字符串内容")
            return content
            
    except FileNotFoundError:
        logger.error(f"找不到文件: {file_path}")
        return None
    except Exception as e:
        logger.error(f"读取文件时发生错误: {e}")
        return None

def start_api_server(txt_data, smis_data=None, u9_orders_data=None, smis_work_order_materials_data=None, port=8888):
    """启动API服务器"""
    try:
        # 将数据设置到处理器类
        TxtDataAPIHandler.txt_data = txt_data
        TxtDataAPIHandler.smis_data = smis_data
        TxtDataAPIHandler.u9_orders_data = u9_orders_data
        TxtDataAPIHandler.smis_work_order_materials_data = smis_work_order_materials_data
        
        server = HTTPServer(('localhost', port), TxtDataAPIHandler)
        
        logger.info("=" * 60)
        logger.info(f"🚀 工单数据API服务器已启动")
        logger.info(f"📡 服务器地址: http://localhost:{port}")
        logger.info(f"🔗 工单API接口: http://localhost:{port}/api/work-orders-from-txt")
        logger.info(f"🏭 SMIS配料岛API接口: http://localhost:{port}/api/smis-inventory")
        logger.info(f"📦 SMIS工单物料API接口: http://localhost:{port}/api/smis-work-order-materials")
        logger.info(f"📋 U9生产订单API接口: http://localhost:{port}/api/u9-production-orders")
        logger.info(f"❤️  健康检查: http://localhost:{port}/api/health")
        logger.info(f"📊 管理面板: http://localhost:{port}/")
        
        if isinstance(txt_data, list):
            logger.info(f"📄 已加载 {len(txt_data)} 条工单数据")
        else:
            logger.info(f"📄 已加载工单数据")
            
        if smis_data:
            if isinstance(smis_data, list):
                logger.info(f"🏭 已加载 {len(smis_data)} 条SMIS配料岛库存数据")
            else:
                logger.info(f"🏭 已加载SMIS配料岛库存数据")
        else:
            logger.info(f"⚠️  未加载SMIS配料岛库存数据")
            
        if u9_orders_data:
            logger.info(f"📋 已加载U9生产订单原始数据文件")
        else:
            logger.info(f"⚠️  未加载U9生产订单数据")
            
        if smis_work_order_materials_data:
            if isinstance(smis_work_order_materials_data, list):
                logger.info(f"📦 已加载 {len(smis_work_order_materials_data)} 条SMIS工单物料数据")
            else:
                logger.info(f"📦 已加载SMIS工单物料数据")
        else:
            logger.info(f"⚠️  未加载SMIS工单物料数据")
            
        logger.info("=" * 60)
        logger.info("按 Ctrl+C 停止服务器")
        
        # 优雅关闭处理
        def signal_handler(sig, frame):
            logger.info("\n🛑 正在关闭服务器...")
            server.shutdown()
            logger.info("✅ 服务器已关闭")
            sys.exit(0)
        
        signal.signal(signal.SIGINT, signal_handler)
        if hasattr(signal, 'SIGTERM'):
            signal.signal(signal.SIGTERM, signal_handler)
        
        server.serve_forever()
        
    except OSError as e:
        if e.errno == 10048:  # Windows: 端口被占用
            logger.error(f"❌ 端口 {port} 已被占用，请尝试其他端口")
            logger.info(f"💡 您可以使用: python {sys.argv[0]} [txt文件路径] [端口号]")
        else:
            logger.error(f"❌ 启动服务器时发生网络错误: {e}")
        sys.exit(1)
    except Exception as e:
        logger.error(f"❌ 启动服务器时发生错误: {e}")
        sys.exit(1)

def main():
    """主函数"""
    # 默认txt文件路径 - 使用当前脚本所在目录
    script_dir = os.path.dirname(os.path.abspath(__file__))
    default_txt_path = os.path.join(script_dir, "smis工单.txt")
    default_smis_path = os.path.join(script_dir, "SMIS配料岛库存数据.txt")
    default_u9_orders_path = os.path.join(script_dir, "u9生产订单.txt")
    default_smis_work_order_materials_path = os.path.join(script_dir, "smis工单物料接口.txt")
    default_port = 8888
    
    # 解析命令行参数
    txt_file_path = default_txt_path
    smis_file_path = default_smis_path
    u9_orders_file_path = default_u9_orders_path
    smis_work_order_materials_file_path = default_smis_work_order_materials_path
    port = default_port
    
    if len(sys.argv) > 1:
        txt_file_path = sys.argv[1]
    if len(sys.argv) > 2:
        smis_file_path = sys.argv[2]
    if len(sys.argv) > 3:
        u9_orders_file_path = sys.argv[3]
    if len(sys.argv) > 4:
        smis_work_order_materials_file_path = sys.argv[4]
    if len(sys.argv) > 5:
        try:
            port = int(sys.argv[5])
        except ValueError:
            logger.error(f"无效的端口号: {sys.argv[5]}")
            sys.exit(1)
    
    # 显示启动信息
    print("=" * 60)
    print("🚀 工单数据API服务器启动程序")
    print("=" * 60)
    print(f"📁 工单数据文件: {txt_file_path}")
    print(f"🏭 SMIS配料岛文件: {smis_file_path}")
    print(f"📦 SMIS工单物料文件: {smis_work_order_materials_file_path}")
    print(f"📋 U9生产订单文件: {u9_orders_file_path}")
    print(f"🌐 服务端口: {port}")
    print("=" * 60)
    
    # 检查工单文件是否存在
    if not os.path.exists(txt_file_path):
        logger.error(f"❌ 工单文件不存在: {txt_file_path}")
        print(f"\n💡 用法: python {sys.argv[0]} [工单文件路径] [SMIS配料岛文件路径] [U9生产订单文件路径] [SMIS工单物料文件路径] [端口号]")
        print(f"📝 示例: python {sys.argv[0]} work_orders.txt smis_inventory.txt u9_orders.txt smis_materials.txt 8888")
        print(f"🔧 默认工单: {default_txt_path}")
        print(f"🔧 默认SMIS: {default_smis_path}")
        print(f"🔧 默认SMIS工单物料: {default_smis_work_order_materials_path}")
        print(f"🔧 默认U9订单: {default_u9_orders_path}")
        sys.exit(1)
    
    # 读取工单txt文件内容
    logger.info(f"📖 正在读取工单文件: {txt_file_path}")
    txt_data = read_txt_file(txt_file_path)
    
    if txt_data is None:
        logger.error("❌ 无法读取或解析工单文件")
        print("\n💡 请确保:")
        print("1. 文件存在且可读")
        print("2. 文件内容是有效的JSON格式")
        print("3. 文件编码是UTF-8")
        sys.exit(1)
    
    # 显示工单数据统计信息
    if isinstance(txt_data, list):
        logger.info(f"✅ 成功加载 {len(txt_data)} 条工单数据")
    elif isinstance(txt_data, dict):
        logger.info(f"✅ 成功加载工单数据（对象格式）")
    else:
        logger.info(f"✅ 成功加载工单数据（{type(txt_data).__name__}格式）")
    
    # 读取SMIS配料岛库存数据（可选）
    smis_data = None
    if os.path.exists(smis_file_path):
        logger.info(f"📖 正在读取SMIS配料岛库存文件: {smis_file_path}")
        smis_data = read_txt_file(smis_file_path)
        
        if smis_data is not None:
            if isinstance(smis_data, list):
                logger.info(f"✅ 成功加载 {len(smis_data)} 条SMIS配料岛库存数据")
            elif isinstance(smis_data, dict):
                logger.info(f"✅ 成功加载SMIS配料岛库存数据（对象格式）")
            else:
                logger.info(f"✅ 成功加载SMIS配料岛库存数据（{type(smis_data).__name__}格式）")
        else:
            logger.warning(f"⚠️  无法读取SMIS配料岛库存文件，将跳过")
    else:
        logger.warning(f"⚠️  SMIS配料岛库存文件不存在: {smis_file_path}")
        logger.info(f"💡 如需加载SMIS配料岛库存数据，请确保文件存在")
    
    # 读取U9生产订单数据（可选）
    u9_orders_data = None
    if os.path.exists(u9_orders_file_path):
        logger.info(f"📖 正在读取U9生产订单文件: {u9_orders_file_path}")
        u9_orders_data = read_txt_file(u9_orders_file_path)
        
        if u9_orders_data is not None:
            logger.info(f"✅ 成功加载U9生产订单原始数据文件")
        else:
            logger.warning(f"⚠️  无法读取U9生产订单文件，将跳过")
    else:
        logger.warning(f"⚠️  U9生产订单文件不存在: {u9_orders_file_path}")
        logger.info(f"💡 如需加载U9生产订单数据，请确保文件存在")
    
    # 读取SMIS工单物料数据（可选）
    smis_work_order_materials_data = None
    if os.path.exists(smis_work_order_materials_file_path):
        logger.info(f"📖 正在读取SMIS工单物料文件: {smis_work_order_materials_file_path}")
        smis_work_order_materials_data = read_txt_file(smis_work_order_materials_file_path)
        
        if smis_work_order_materials_data is not None:
            if isinstance(smis_work_order_materials_data, list):
                logger.info(f"✅ 成功加载 {len(smis_work_order_materials_data)} 条SMIS工单物料数据")
            elif isinstance(smis_work_order_materials_data, dict):
                logger.info(f"✅ 成功加载SMIS工单物料数据（对象格式）")
            else:
                logger.info(f"✅ 成功加载SMIS工单物料数据（{type(smis_work_order_materials_data).__name__}格式）")
        else:
            logger.warning(f"⚠️  无法读取SMIS工单物料文件，将跳过")
    else:
        logger.warning(f"⚠️  SMIS工单物料文件不存在: {smis_work_order_materials_file_path}")
        logger.info(f"💡 如需加载SMIS工单物料数据，请确保文件存在")
    
    try:
        # 启动API服务器
        start_api_server(txt_data, smis_data, u9_orders_data, smis_work_order_materials_data, port)
            
    except KeyboardInterrupt:
        logger.info("\n👋 用户中断操作")
        sys.exit(0)
    except Exception as e:
        logger.error(f"❌ 运行时发生错误: {e}")
        sys.exit(1)

if __name__ == "__main__":
    main()
